package com.lu.common.exception;

import com.lu.common.config.Constant;
import com.lu.common.config.ServerConfig;
import com.lu.common.utils.HttpServletUtils;
import com.lu.common.utils.R;
import com.lu.common.utils.ShiroUtils;
import com.lu.common.utils.TokenUtils;
import com.lu.system.sysLog.domain.SysLog2DO;
import com.lu.system.sysLog.service.SysLog2Service;
import com.lu.system.user.domain.UserDO;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 异常处理器
 */
@RestControllerAdvice
public class BDExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SysLog2Service logService;
    @Autowired
    private ServerConfig serverConfig;

//
//    /**
//     * 自定义异常
//     */
//    @ExceptionHandler(BDException.class)
//    public R handleBDException(BDException e) {
//        logger.error(e.getMessage(), e);
//        R r = new R();
//        r.put("code", e.getCode());
//        r.put("msg", e.getMessage());
//        return r;
//    }
//
//    @ExceptionHandler(DuplicateKeyException.class)
//    public R handleDuplicateKeyException(DuplicateKeyException e) {
//        logger.error(e.getMessage(), e);
//        return R.error("数据库中已存在该记录");
//    }
//
//    @ExceptionHandler(org.springframework.web.servlet.NoHandlerFoundException.class)
//    public R noHandlerFoundException(org.springframework.web.servlet.NoHandlerFoundException e) {
//        logger.error(e.getMessage(), e);
//        return R.error(404, "没找找到页面");
//    }

    /**
     * Controller抛出的Exception异常，统一处理
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler({Exception.class})
    public Object handleException(Exception e, HttpServletRequest request) throws IOException {
        logger.error("error级别的日志信息：",e.getMessage());
        if (HttpServletUtils.jsAjax(request)) {
            return R.error(500, "服务器错误，请联系管理员");
        }
        return new ModelAndView("error/500");
    }

    /**
     * 保存系统日志
     * @param e 异常信息
     * @param request  请求头
     */
    public void saveSysLog(Exception e, HttpServletRequest request){
        String errorMsg = e.getMessage();
        String url = request.getRequestURI();
        Map<String, String[]> map = request.getParameterMap();
        String params = "";
        for(String key : map.keySet()){
            String[] ss = map.get(key);
            String val = "";
            for(String s : ss){
                val += s+"|";
            }
            val = val.substring(0,val.length()-1);
            if(!key.equals("access_token")){
                params += "key:"+key+",value:"+val+"&";
            }
            System.out.println(params);
        }
        params = params.substring(0,params.length()-1);

        Long userId = null;
        String username = "";
        try {
            UserDO userDO = TokenUtils.parseJwtForUserInfo(request);
            userId = userDO.getUserId();
            username = userDO.getUsername();
        } catch (Exception e1) {
            errorMsg += "------token失效！";
            logger.error("token失效!", e1);
        }
        SysLog2DO logDO = new SysLog2DO();
        logDO.setCreateTime(new Date());
        logDO.setUpdateTime(new Date());
        logDO.setUserId(userId);
        logDO.setUserName(username);
        logDO.setUrl(url);
        logDO.setParams(params);
        logDO.setHost(request.getRemoteHost());
        logDO.setPort(request.getRemotePort()+"");
        logService.save(logDO);
        logger.error(e.getMessage(), e);
    }

}
